package com.myapp.video.home.mvp.ui.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;

import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.kjsdfgk.hjmdsf.app.entity.FavoriteItem;
import com.kjsdfgk.hjmdsf.app.entity.HistoryItem;
import com.lksdkjs.live.R;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.model.VideoOptionModel;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.leancloud.AVObject;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class PlayVideoActivity extends AppCompatActivity {
    StandardGSYVideoPlayer videoPlayer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_video);

        videoPlayer =  (StandardGSYVideoPlayer)findViewById(R.id.videoPlayer);
        /**此中内容：优化加载速度，降低延迟*/
        VideoOptionModel videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "rtsp_transport", "tcp");
        List<VideoOptionModel> list = new ArrayList<>();
        list.add(videoOptionModel);
        videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "rtsp_flags", "prefer_tcp");
        list.add(videoOptionModel);
        videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "allowed_media_types", "video"); //根据媒体类型来配置
        list.add(videoOptionModel);
        videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", 20000);
        list.add(videoOptionModel);
        videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "buffer_size", 1316);
        list.add(videoOptionModel);
        videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "infbuf", 1);  // 无限读
        list.add(videoOptionModel);
        videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzemaxduration", 100);
        list.add(videoOptionModel);
        videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", 10240);
        list.add(videoOptionModel);
        videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "flush_packets", 1);
        list.add(videoOptionModel);
        //  关闭播放器缓冲，这个必须关闭，否则会出现播放一段时间后，一直卡主，控制台打印 FFP_MSG_BUFFERING_START
        videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 0);
        list.add(videoOptionModel);
        GSYVideoManager.instance().setOptionModelList(list);
        String source1 = getIntent().getStringExtra("url");
        String title = getIntent().getStringExtra("title");
        String img = getIntent().getStringExtra("img");
        videoPlayer.setUp(source1, true, title);
        //videoPlayer.getTitleTextView().setVisibility(View.GONE);
        videoPlayer.getBackButton().setOnClickListener(v -> finish());
        videoPlayer.startPlayLogic();

        HistoryItem historyItem = new HistoryItem();
        historyItem.img = img;
        historyItem.url = source1;
        historyItem.title = title;
        historyItem.time = TimeUtils.getNowString();
        historyItem.type = 1000;
        String userName = SPUtils.getInstance().getString("account", "");
        historyItem.userName = userName;
        List<HistoryItem> itemList = LitePal.where("url=?",source1).find(HistoryItem.class);
        for (HistoryItem item : itemList){
            item.delete();
        }
        historyItem.save();

        CheckBox checkBox = findViewById(R.id.checkbox);
        try {
            List<FavoriteItem> itemListxxxx = LitePal.where("url=? and userName=?",source1,userName).find(FavoriteItem.class);
            if (itemListxxxx.size() > 0){
                checkBox.setChecked(true);
            }else {
                checkBox.setChecked(false);
            }
        }catch (Exception e){
            AVObject avObject = new AVObject();// 新建 AVUser 对象实例
            avObject.setClassName("Log");
            String info = DeviceUtils.getManufacturer() + DeviceUtils.getModel();
            avObject.put("crash" ,"com.lksdkjs.live---->" + e.toString());//
            avObject.put("info", info);
            avObject.put("time", TimeUtils.getNowString());
            avObject.saveInBackground().subscribe(new Observer<AVObject>() {
                @Override
                public void onSubscribe(Disposable disposable) {

                }

                @Override
                public void onNext(AVObject avObject) {
                    System.out.println("saveObject field finished.");

                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }
            });
        }


        checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked){
                FavoriteItem favoriteItem = new FavoriteItem();
                favoriteItem.img = img;
                favoriteItem.url = source1;
                favoriteItem.title = title;
                favoriteItem.time = TimeUtils.getNowString();
                favoriteItem.type = 1000;
                favoriteItem.userName = userName;
                favoriteItem.save();
            }else {

                List<FavoriteItem> itemList3 = LitePal.where("url=? and userName=?",source1 ,userName).find(FavoriteItem.class);
                for (FavoriteItem item : itemList3){
                    item.delete();
                }
            }
        });
    }


    @Override
    protected void onPause() {
        super.onPause();
        videoPlayer.onVideoPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        videoPlayer.onVideoResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();

    }

    @Override
    public void onBackPressed() {
        //先返回正常状态
        //释放所有
        videoPlayer.setVideoAllCallBack(null);
        super.onBackPressed();
    }
}
